<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 页面已完成
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-input
          v-model="query.username"
          placeholder="用户名"
          class="handle-input mr10"
          clearable
          @keyup.native.enter="handleSearch()"
        ></el-input>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button
          type="primary"
          @click="handleAdd"
          v-if="smPermissions.includes('sys:user:save')"
          >新增</el-button
        >
        <el-button
          type="danger"
          class="handle-del"
          @click="delAllSelection"
          v-if="smPermissions.includes('sys:user:delete')"
          >删除</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
        :default-sort="{ prop: 'createDate', order: 'descending' }"
        @sort-change="sortChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>

        <el-table-column
          prop="username"
          label="用户名"
          align="center"
          sortable
        ></el-table-column>
        <el-table-column
          prop="deptName"
          label="所属部门"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="手机号"
          align="center"
          sortable
        ></el-table-column>
        <el-table-column label="状态" align="center" sortable>
          <template slot-scope="scope">
            <el-tag>{{ scope.row.status === 1 ? "正常" : "异常" }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="createDate"
          label="创建时间"
          sortable
        ></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleEdit(scope.$index, scope.row)"
              v-if="smPermissions.includes('sys:user:update')"
              >编辑</el-button
            >
            <el-button
              type="text"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="smPermissions.includes('sys:user:delete')"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          background
          layout="total,sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 30]"
          @size-change="handleSizeChange"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 新增&&编辑弹出框 -->
    <el-dialog :title="title" :visible.sync="editVisible" width="50%">
      <el-form ref="form" :model="form" label-width="auto" :rules="rules">
        <el-form-item label="用户名">
          <el-input v-model="form.username" clearable></el-input>
        </el-form-item>
        <el-form-item label="所属部门">
          <div class="block">
            <el-cascader
              v-model="deptvalue"
              @change="handleChange"
              :options="deptList"
              :props="{ checkStrictly: true }"
              ref="cascader"
              clearable
            ></el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            clearable
            v-model="form.password"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            type="password"
            clearable
            v-model="form.confirmPassword"
          ></el-input>
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input clearable v-model="form.realName"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender" size="medium">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input clearable v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input clearable v-model="form.mobile"></el-input>
        </el-form-item>
        <el-form-item label="角色配置">
          <div class="block">
            <el-cascader
              :options="roleList"
              v-model="rolevalue"
              @change="handleMultipleChange"
              :props="{ multiple: true, checkStrictly: true }"
              clearable
            ></el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status" size="medium">
            <el-radio :label="0">停用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { sysUserMixin } from "common/js/userManage";
import util from "utils/util";
import { mapGetters } from "vuex";
// console.log(sysUserMixin);
export default {
  name: "SysUser",
  // mixins: [sysUserMixin],

  data() {
    var validatePassword = (rule, value, callback) => {
      if (value === undefined) {
        callback(new Error("请输入密码"));
      } else {
        if (this.form.password !== "") {
          callback();
        }
      }
    };
    var validateConfirmPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      smPermissions: [],
      roleList: [],
      selectRoles: [],
      rolevalue: [],
      deptvalue: [],
      title: "",
      increaseFlag: false,
      editFlag: false,
      deptList: [
        {
          value: "",
          label: "",
          children: [
            {
              value: "",
              label: "",
            },
          ],
        },
      ],
      query: {
        order: "",
        orderField: "",
        pageIndex: 1,
        pageSize: 20,
        username: "",
      },

      tableData: [
        {
          id: "",
          username: "",
          deptName: "",
          email: "",
          mobile: "",
          status: "",
          createDate: "",
          realName: "",
          headUrl: "",
          deptId: "",
          superAdmin: "",
          roleIdList: "",
          gender: "",
        },
      ],
      multipleSelection: [],
      delList: [],
      editVisible: false,
      pageTotal: 0,
      form: {
        username: "",
        password: "",
        confirmPassword: "",
        realName: "",
        gender: "",
        email: "",
        mobile: "",
        status: "",
        deptName: "",
      }, // 无角色配置和所属部门
      rules: {
        password: [
          { required: true, validator: validatePassword, trigger: "blur" },
        ],
        confirmPassword: [
          {
            required: true,
            validator: validateConfirmPassword,
            trigger: "blur",
          },
        ],
      },
      idx: -1,
      ids: [],
    };
  },

  created() {
    // 真实数据
    this.getSysUser({});
    this.smPermissions = this.permissions;
  },
  computed: {
    ...mapGetters(["permissions"]),
  },
  methods: {
    // 获取数据
    getSysUser({
      order = this.query.order,
      orderField = this.query.orderField,
      page = this.query.pageIndex,
      limit = this.query.pageSize,
      username = this.query.name,
      _t = Date.now(),
    }) {
      this.$axios
        .get("/sys/user/page", {
          params: {
            order,
            orderField,
            page,
            limit,
            username,
            _t,
          },
        })
        .then((res) => {
          if (res.status !== 200) {
            return;
          }
          console.log(res);
          var data = res.data.data;
          this.pageTotal = data.total || 0;
          var dataList = data.list;
          this.tableData = [];
          for (var i = 0; i < dataList.length; i++) {
            this.tableData.push({
              id: dataList[i].id,
              username: dataList[i].username,
              deptName: dataList[i].deptName,
              email: dataList[i].email,
              mobile: dataList[i].mobile,
              status: dataList[i].status,
              createDate: dataList[i].createDate,
              realName: dataList[i].realName,
              headUrl: dataList[i].headUrl,
              deptId: dataList[i].deptId,
              superAdmin: dataList[i].superAdmin,
              roleIdList: dataList[i].roleIdList,
              gender: dataList[i].gender,
            });
          }
          console.log(this.tableData);
        })
        .catch((err) => {
          return this.$message.error(err.$message);
        });
    },
    // 单选所属部门
    handleChange(value) {
      console.log(value);
      this.form.deptName = value[value.length - 1];
      console.log(this.form.deptName);
    },
    // 多选角色
    handleMultipleChange(value) {
      console.log(value);
      this.selectRoles = value;
    },
    // 新增
    handleAdd() {
      this.editVisible = true;
      this.editFlag = false;
      this.title = "新增";
      this.form = {};
      // 初始化所属部门
      this.initDeptList();
      // 初始化角色配置
      this.initRoleList();

      // 标记
      this.increaseFlag = true;
    },
    circle(deptName, deptList) {
      console.log(deptName, deptList);
      for (var i = 0; i < deptList.length; i++) {
        if (deptList[i].name == deptName) {
          this.deptId = deptList[i].id;
          return deptList[i].id; // 返回值返回到了this.circle()中去了
        } else if (deptList[i].children && deptList[i].children.length) {
          console.log(deptName, deptList[i].children);
          this.circle(deptName, deptList[i].children);
        }
      }
    },
    // 递归思想: 根据deptName查找id
    getDeptId(deptName, deptList) {
      console.log(deptName, deptList);
      this.circle(deptName, deptList);
      return this.deptId;
    },

    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(this.multipleSelection);
    },
    delAllSelection() {
      var ids = this.multipleSelection.map((item) => {
        return item.id;
      });
      util.delete.call(this, "/sys/user", "", ids, this.getSysUser);
    },
    // 根据选择的角色名字 获得id
    getRoleIdList(roleList, selectRoles) {
      console.log(roleList, selectRoles);
      var array = [];
      for (var item of roleList) {
        for (var val of selectRoles) {
          if (val[0] == item.name) {
            array.push(item.id);
          }
        }
      }
      return array;
    },
    // 根据选择的
    saveEdit() {
      // 新增确定进入
      if (this.increaseFlag) {
        console.log("新增");
        // 得到成功提示
        this.$axios
          .post("/sys/user", {
            username: this.form.username,
            deptId: this.getDeptId(this.form.deptName, this.deptList),
            deptName: this.form.deptName,
            password: this.form.password,
            comfirmPassword: this.form.confirmPassword,
            realName: this.form.realName,
            gender: this.form.gender,
            email: this.form.email,
            mobile: this.form.mobile,
            roleIdList: this.getRoleIdList(this.roleList, this.selectRoles),
            status: this.form.status,
            headUrl: null,
            createDate: null,
            superAdmin: 0,
          })
          .then(({ data: res }) => {
            if (res.code !== 0) {
              this.$message.error(res.data.msg);
            }
            this.editVisible = false;
            this.$message.success(`新增一条数据`);
            this.increaseFlag = false;
            // 刷新
            this.getSysUser({});
          })
          .catch(() => {});
      }

      // 编辑确定进入
      if (this.editFlag) {
        this.$message.success(`修改第 ${this.idx + 1} 行成功`);
        this.$set(this.tableData, this.idx, this.form);
        this.$axios
          .put("/sys/user", {
            id: this.form.id,
            username: this.form.username,
            deptId: this.getDeptId(this.form.deptName, this.deptList),
            deptName: this.form.deptName,
            password: this.form.password,
            comfirmPassword: this.form.comfirmPassword,
            realName: this.form.realName,
            gender: this.form.gender,
            email: this.form.email,
            mobile: this.form.mobile,
            roleIdList: this.getRoleIdList(this.roleList, this.selectRoles),
            status: this.form.status,
            headUrl: this.form.headUrl,
            createDate: this.form.createDate,
            superAdmin: this.form.superAdmin,
          })
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return;
            }
            // 返回成功提示
            this.editFlag = false;
            this.editVisible = false;
            // 刷新
            this.getSysUser({});
          })
          .catch(() => {});
      }
    },
    // 编辑操作
    handleEdit(index, row) {
      this.title = "编辑";
      this.idx = index;
      this.form = row;
      this.editVisible = true;
      this.form.deptName = "";
      this.editFlag = true;
      this.increaseFlag = false;

      // 获取单个用户信息
      this.$axios
        .get(`/sys/user/${row.id}`, {
          params: { _t: Date.now() },
        })
        .then((res) => {
          if (res.status !== 200) {
            return;
          }
          this.form = {};
          this.form = res.data.data;
          console.log(this.form);
          // 初始化所属部门
          this.initDeptList();
          // 初始化角色配置
          this.initRoleList();
        })
        .catch((err) => {
          return this.$message.error(err.message);
        });
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.getSysUser({});
    },
    handleSizeChange(val) {
      this.$set(this.query, "pageSize", val);
      this.getSysUser({});
    },
    // 删除操作
    handleDelete(index, row) {
      this.ids[0] = row.id;
      util.delete.call(this, "/sys/user", index, this.ids, this.getSysUser);
    },
    // 初始化所属部门
    initDeptList() {
      return this.$axios
        .get("/sys/dept/list", {
          params: {
            _t: Date.now(),
          },
        })
        .then((res) => {
          if (res.status !== 200) {
            this.$message.error("获取数据失败");
          }
          var data = res.data.data;
          // 调用递归
          this.addLabelAttribute(data);
          this.deptList = data;
          console.log(this.deptList);
          this.deptList.map((item) => {
            if (item.id == this.form.deptId) {
              this.deptvalue = item.name;
            }
          });
        });
    },
    // 初始化角色配置
    initRoleList() {
      return this.$axios
        .get("/sys/role/list", {
          params: { _t: Date.now() },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.addLabelAttribute(res.data);
          this.roleList = res.data;
          this.rolevalue = [];
          console.log("角色列表", this.roleList);
          for (var val of this.form.roleIdList) {
            this.roleList.map((item) => {
              if (val == item.id) {
                this.rolevalue.push(item.name);
              }
            });
          }
        });
    },
    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, "pageIndex", 1);
      var params = {
        order: this.query.order,
        orderField: this.query.orderField,
        page: this.query.pageIndex,
        limit: this.query.pageSize,
        username: this.query.username,
        _t: Date.now(),
      };
      this.tableData = [];
      this.getSysUser(params);
    },

    // 递归思想: 添加label属性
    addLabelAttribute(arr) {
      for (var i = 0; i < arr.length; i++) {
        if ("children" in arr[i] && arr[i].children.length !== 0) {
          arr[i].label = arr[i].name;
          arr[i].value = arr[i].name;
          this.addLabelAttribute(arr[i].children);
        } else if ("children" in arr[i] && arr[i].children.length === 0) {
          arr[i].label = arr[i].name;
          arr[i].value = arr[i].name;
          delete arr[i].children;
        } else if (!("children" in arr[i])) {
          arr[i].label = arr[i].name;
          arr[i].value = arr[i].name;
        }
      }
    },
    // 表头排序
    sortChange({ column, prop, order }) {
      prop = prop === "createDate" ? "create_date" : prop;
      this.$set(this.query, "orderField", prop);
      if (order === "ascending") {
        this.$set(this.query, "order", order.substr(0, 3));
        this.getSysUser({});
      } else if (order === "descending") {
        this.$set(this.query, "order", order.substr(0, 4));
        this.getSysUser({});
      }
    },
  },
  watch: {
    deptvalue() {
      if (this.$refs.cascader) {
        this.$refs.cascader.dropDownVisible = false;
      }
    },
    "$route.path": function(newVal, oldVal) {
      if (newVal == "/sys-manage") {
        this.smPermissions = this.permissions;
      }
    },
    // 刷新浏览器时触发
    permissions: function(newVal, oldVal) {
      // console.log(newVal, oldVal);
      this.smPermissions = newVal;
    },
  },
};
</script>

<style scoped lang="scss">
@import url("../../common/css/index.css");
</style>
